package com.pet_service.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pet_service.entity.Permission;
import com.pet_service.result.Result;
import com.pet_service.service.PermissionService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author 邹全伸
 * @version 1.0
 * @date 2025-09-24 11:21
 */
@Slf4j
@Tag(name = "权限模块")
@RestController
@RequestMapping("/permissions")
public class PermissionController {

    @Resource
    private PermissionService permissionService;

    //  查询所有菜单树信息
    @GetMapping("/treeList")
    @PreAuthorize("hasAuthority('system:menu:view')")
    public Result treeList() {
        List<Permission> permissionList =
                permissionService.list(new QueryWrapper<Permission>().orderByAsc("order_num"));
        return Result.ok(200, "treeMenu", permissionService.buildTreePermission(permissionList));
    }

    // 保存或更新权限
    @PostMapping("/saveOrUpdatePermission")
    @PreAuthorize("hasAuthority('system:permission:create')" + "||" + "hasAuthority('system:permission:edit')")
    public Result saveOrUpdatePermission(@RequestBody  Permission permission) {
        log.info("-------------------保存或更新权限:{}", permission.getPermission_name());

        if(permission.getId() == null || permission.getId() == 0) {
            // 新增
            permission.setCreated_at(new Date());
            boolean flag = permissionService.save(permission);
            return flag ? Result.ok("权限添加成功!") : Result.fail("权限添加失败!");
        } else {
            // 更新
            permission.setUpdated_at(new Date());
            boolean flag = permissionService.updateById(permission);
            return flag ? Result.ok("权限修改成功!") : Result.fail("权限修改失败!");
        }
    }

    // 查询权限
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:menu:view')")
    public Result findById(@PathVariable(value = "id")Integer id){
        Permission permission = permissionService.getById(id);
        return Result.ok(permission);
    }

    // 删除权限
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('system:permission:delete')")
    public Result delete(@PathVariable(value = "id")Integer id){
        log.info("-------------------删除权限:{}", id);
        return  permissionService.removePermissionByPid(id);
    }
}